﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;
using System.Collections.Generic;
using TarreOA.TarreOADAL;

public partial class Flow_Info_flow_uploadaffixfile : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
            if (Request.QueryString.Get("WRID") != null)
            {
                int workid = int.Parse(Request.QueryString.Get("WRID"));
                this.findaffixfiles(workid);
                ViewState["workid"] = workid;
            }
    }

    /// <summary>
    /// 查询当前工作编号的附加信息并填充到affixfilelist中
    /// </summary>
    /// <param name="workid"></param>
    private void findaffixfiles(int workid)
    {
        SqlConnection sqlconn = null;
        SqlCommand sqlcmd = null;
        SqlDataReader sqldr = null;
        try
        {
            sqlconn = SQLManager.GetConn();
            string sql = "select * from flow_newworkaffixfile where workid = " + workid.ToString();
            sqlconn.Open();
            sqlcmd = new SqlCommand(sql, sqlconn);
            sqldr = sqlcmd.ExecuteReader();
            if (affixfilelist.Items.Count > 0)
                affixfilelist.Items.Clear();
            if (sqldr.HasRows)
                while (sqldr.Read())
                {
                    ListItem item = new ListItem();
                    item.Text = (string)sqldr["filename"];
                    item.Value = sqldr["id"].ToString();
                    affixfilelist.Items.Add(item);
                }
            if (affixfilelist.Items.Count > 0)
                btndelete.Enabled = true;
            else
                btndelete.Enabled = false;
        }
        catch (Exception ex)
        {
            Response.Write("错误原因:<font color=red>" + ex.Message + "</font><br />");
            Response.Write("错误来源:<font color=red>" + ex.TargetSite + "</font><br />");
        }
        finally
        {
            this.closesql(sqlconn, sqldr);
        }
    }

    /// <summary>
    /// 关闭相关sql对象(SqlConnection, SqlDataReader)
    /// </summary>
    /// <param name="sqlconn"></param>
    /// <param name="sqldr"></param>
    private void closesql(SqlConnection sqlconn, SqlDataReader sqldr)
    {
        try
        {
            if (sqlconn != null)
                if (sqlconn.State == ConnectionState.Open)
                {
                    sqlconn.Close();
                    sqlconn.Dispose();
                }
            if (sqldr != null)
            {
                sqldr.Close();
                sqldr.Dispose();
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
    }

    /// <summary>
    /// 上传按钮点击事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void htnupload_Click(object sender, EventArgs e)
    {
        int workid = 0;
        if (ViewState["workid"] != null)
            workid = (int)ViewState["workid"];
        if (affixupload.HasFile && workid != 0)
        {
            DirectoryInfo dirinfo = new DirectoryInfo(Server.MapPath("work_upload"));
            if (!dirinfo.Exists)
                dirinfo.Create();
            string suffix = affixupload.FileName.Substring(affixupload.FileName.LastIndexOf("."));
            string newfilename = DateTime.Now.ToFileTime().ToString() + suffix;
            affixupload.SaveAs(Server.MapPath("work_upload\\" + newfilename));
            if (this.saveaffixfile(workid, affixupload.FileName, Server.MapPath("work_upload\\" + newfilename)))
            {
                ClientScript.RegisterStartupScript(GetType(), "", "alert('上传成功!')", true);
                this.findaffixfiles(workid);
            }
            else
            {
                ClientScript.RegisterStartupScript(GetType(), "", "alert('上传失败,请与有关人员联系!')", true);
            }
        }
        ViewState["workid"] = workid;
    }

    /// <summary>
    /// 保存上传附件信息到数据库
    /// </summary>
    /// <param name="workid"></param>
    /// <param name="filename"></param>
    /// <param name="filepath"></param>
    private bool saveaffixfile(int workid, string filename, string filepath)
    {
        SqlConnection sqlconn = null;
        SqlCommand sqlcmd = null;
        try
        {
            sqlconn = SQLManager.GetConn();
            string sql = "insert into flow_newworkaffixfile values(@filename,@filepath,@workid)";
            sqlconn.Open();
            sqlcmd = new SqlCommand(sql, sqlconn);
            sqlcmd.Parameters.Add(new SqlParameter("@filename", filename));
            sqlcmd.Parameters.Add(new SqlParameter("@filepath", filepath));
            sqlcmd.Parameters.Add(new SqlParameter("@workid", workid));
            if (sqlcmd.ExecuteNonQuery() == 1)
                return true;
        }
        catch (Exception ex)
        {
            Response.Write("错误原因:<font color=red>" + ex.Message + "</font><br />");
            Response.Write("错误来源:<font color=red>" + ex.TargetSite + "</font><br />");
        }
        finally
        {
            this.closesql(sqlconn, null);
        }
        return false;
    }

    /// <summary>
    /// 附件删除按钮点击事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btndelete_Click(object sender, EventArgs e)
    {
        int workid = 0;
        if (ViewState["workid"] != null)
            workid = (int)ViewState["workid"];
        if (affixfilelist.Items.Count > 0 && workid != 0)
        {
            string sqldel = "delete from flow_newworkaffixfile where id in (0";
            string sqlfind = "select filepath from flow_newworkaffixfile where id in (0";
            string ids = "";
            List<string> filepathlist = new List<string>();
            for (int i = 0; i < affixfilelist.Items.Count; i++)
            {
                if (affixfilelist.Items[i].Selected)
                {
                    ids += ("," + affixfilelist.Items[i].Value);
                }
            }
            if (!"".Equals(ids))
            {
                sqldel += (ids + ")");
                sqlfind += (ids + ")");
                SqlConnection sqlconn = null;
                SqlCommand sqlcmd = null;
                SqlDataReader sqldr = null;
                try
                {
                    sqlconn = SQLManager.GetConn();
                    sqlconn.Open();
                    sqlcmd = new SqlCommand(sqlfind, sqlconn);
                    sqldr = sqlcmd.ExecuteReader();
                    if(sqldr.HasRows)
                        while (sqldr.Read())
                        {
                            filepathlist.Add((string)sqldr["filepath"]);
                        }
                    sqldr.Close();
                    sqlcmd = new SqlCommand(sqldel, sqlconn);
                    int count = sqlcmd.ExecuteNonQuery();
                    if (count == filepathlist.Count)
                    {
                        foreach (string filepath in filepathlist)
                        {
                            FileInfo fi = new FileInfo(filepath);
                            if (fi.Exists)
                                fi.Delete();
                        }
                        ClientScript.RegisterStartupScript(GetType(), "", "alert('删除完毕!')", true);
                    }
                    else
                    {
                        ClientScript.RegisterStartupScript(GetType(), "", "alert('删除记录数和文件数不对应,请联系有关人员检查问题!')", true);
                    }
                }
                catch (Exception ex)
                {
                    Response.Write("错误原因:<font color=red>" + ex.Message + "</font><br />");
                    Response.Write("错误来源:<font color=red>" + ex.TargetSite + "</font><br />");
                }
                finally
                {
                    this.closesql(sqlconn, sqldr);
                }
            }
            this.findaffixfiles(workid);
        }
        ViewState["workid"] = workid;
    }
}
